package com.lzy.files.service.impl;

import com.aliyun.oss.*;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.lzy.files.resource.FileResource;
import com.lzy.files.service.UploaderService;
import com.lzy.utils.extend.AliyunResource;
import idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;

@Service
public class UploaderServiceImpl implements UploaderService {

    @Autowired
    public FastFileStorageClient fastFileStorageClient;
    @Autowired
    private AliyunResource aliyunResource;
    @Autowired
    private FileResource fileResource;
    @Autowired
    private Sid sid;

    @Override
    public String UploadFdfs(MultipartFile file,String fileExtName) throws Exception {
       StorePath storePath =  fastFileStorageClient.uploadFile(file.getInputStream(),
                                         file.getSize(),
                                         fileExtName,
                              null);
       return storePath.getFullPath();
    }

    @Override
    public String UploadOSS(MultipartFile file, String userId, String fileExtName) throws Exception {
        // 构建ossClient
        OSS ossClient = new OSSClientBuilder()
                .build(fileResource.getEndpoint(),
                        aliyunResource.getAccessKeyID(),
                        aliyunResource.getAccessKeySecret());

        // 上传网络流
        InputStream inputStream = file.getInputStream();

        String fileName = sid.nextShort();
        // 上传专属目录
        String myObjectName = fileResource.getObjectName() + "/" + userId + "/"
                + fileName + "." + fileExtName;

        ossClient.putObject(fileResource.getBucketName(), myObjectName, inputStream);
        ossClient.shutdown();

        return myObjectName;
    }

}
